package com.content.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.content.model.po.CourseCategory;
import com.content.model.vo.AllCategoryResult;
import com.content.service.CourseBaseService;
import com.content.service.CourseCategoryService;
import com.content.service.mapper.CourseCategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;
    @Override
    public List<AllCategoryResult> getAllCategory(String id) {
        List<AllCategoryResult> allCategory = courseCategoryMapper.getAllCategory(id);

        //对返回的数据进行处理
        List<AllCategoryResult> list = new ArrayList<>();

        //转换为map集合，方便等下根据id获得节点
        Map<String, AllCategoryResult> map = allCategory.stream()./*filter(item->id.equals(item.getId())).*/collect(Collectors.toMap(CourseCategory::getId, value -> value, (k1, k2) -> k2));

        allCategory.stream().forEach(p -> {
            if(p.getParentid().equals("1")){
                list.add(p);
            }

            //找到当前节点的父节点
            AllCategoryResult parentNode = map.get(p.getParentid());
            if(parentNode != null){
                if(parentNode.getChildrenTreeNodes() == null){
                    parentNode.setChildrenTreeNodes(new ArrayList<>());
                }
                //下面开始往子节点中放属性
                parentNode.getChildrenTreeNodes().add(p);
            }
        });

        return list;
    }
}
